import React, { useRef, useEffect, useState } from "react";
import { Image, Select, Form, Modal, message, Dropdown, Tooltip, Space, Button } from "antd";
import { CommonModal } from "@/views/components/CommonModal";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import { SearchCheckboxTable } from "@/views/components/SearchTable/index";
import { useTableConfig } from "@/views/components/SearchTable/hooks/useTableConfig";
import PickAssignmentModal from "./component/PickAssignmentModal";
import SupplierAssignmentModal from "./component/SupplierAssignmentModal";
import PrintOnlyCodeModal from "./component/PrintOnlyCodeModal";
import ProductAbnormalModal from "./component/ProductAbnormalModal";
import UnProductAbnormalModal from "./component/UnProductAbnormalModal";
import OnlyCodeDispositionModal from "./component/OnlyCodeDispositionModal";
import NahuoConfigModal from './component/NahuoConfig';
import SelectActions from "@/views/components/SelectActions";
import OrderDetailModal from "@/pages/OrderModule/orderList/components/Actions/common/OrderDetailModal/index.jsx";
import ActionExportExcelModal from "./component/ActionExportExcelModal"; // 导出弹窗
import useColumns from "./cloumns";
import { getFmcgpurchasesList, getSupplierInfo, queryTakeUserList, queryAreaCode, updatePrintStatus, saveCodePrintTask, getKuaiMaiPrint, batchPushGoods, beforeCancelMarkExc } from "./service";
import { hiprintTipsModal } from "@/utils/utils.jsx";
import { usePrintUniqueCode } from "@/views/hooks/usePrintUniqueCode";
import IconFont from '@/components/IconFont';
import { getOrderList } from "./service";
import PrintKmModal from "./component/PrintkmModal";
import { useLocation } from "react-router-dom";
import BatchPushGoodsModal from "./component/BatchPushGoodsModal";
import UniqueCodeLog from "./component/UniqueCodeLog";
import { CloudDownloadOutlined } from '@ant-design/icons';
import { getCurrentUser } from "@/utils/authority";

const printOptions = [
	{ key: "1", label: "针对所选项" },
	{ key: "2", label: "针对筛选项" },
	{ key: "3", label: "针对全部项" }
]

const FmcmPurchasePage = () => {
	const [visible, setVisible] = useState(0);
	const [printVisible, setPrintVisible] = useState(false); //打印弹窗
	const [printParams, setPrintParams] = useState({});
	const [printType, setPrintType] = useState({});
	const [recordItem, setRecordItem] = useState({}); //每行数据
	const [selectedWarehouse, setSelectedWarehouse] = useState(null);
	const [AreaValue, setAreaValue] = useState(null);
	const [userData, setUserData] = useState([]); // 拿货员列表
	const [takeGoods, setTakeGoods] = useState(null);
	const [ApiData, setApiData] = useState({});
	const [shopAddress, setShopAddress] = useState({});
	const [list, setList] = useState({});
	const [total, setTotal] = useState(0);
	const refTimeSort = useRef();
	const tableRequest = getFmcgpurchasesList;
	const areaOption = useRef();
	const [row, setRow] = useState({});
	const [orderDetailVisible, setOrderDetailVisible] = useState(false); //订单详情visible

	const [createTaskData, setCreateTaskData] = useState({});
	//打印数据
	const [printData, setPrintData] = useState([]);
	const [printConfig, setPrintConfig] = useState({});
	// 批量推送数据
	const [pushData, setPushData] = useState();

	const location = useLocation();

	const commonHandleClick = (status, record) => {
		console.log(status, record)
		if (status === 6 || status === 2) {
			setVisible(status);
		} else if (status == 7) {
			if (!selectedRows.length || !selectedRows.every(item => item.status == 'wait-pickup')) {
				message.warning("请选择“待拿货”商品");
			} else {
				const isPushStatus = selectedRows.some(item => item.pushStatus && item.pushStatus == 1);
				const isHasPrinter = selectedRows.every(item => item.hasPrinter && item.hasPrinter == 1);
				if (isPushStatus || !isHasPrinter) {
					return Modal.info({
						title: '提示',
						icon: <IconFont type="iconjingshi"/>,
						content: isPushStatus ? '选择的商品中有已推送商品，请勿重复推送' : '选择的商品中有供应商未安装打印机，无法推送',
						okText: '知道了',
					})
				}
				const params = selectedRows.map(item => ({ code: item.code, storeId: item.supplierId }));
				batchPushGoodsToSupplier(params, 'batch');
			}
		} else {
			console.log(selectedRows, record)
			if (selectedRows.length || record) {
				setVisible(status);
			} else {
				Modal.info({ centered: true, content: "请选择操作数据" });
			}
		}
	};
	const handleWarehouseChange = value => {
		setSelectedWarehouse(value);
	};
	const handleAreaValueChange = value => {
		setAreaValue(value);
	};

	// 查看详情
	async function handleOpenOrderDetailVisible(record) {
		const { data, success } = await getOrderList({ snArr: [record.systemNo] });
		if (success) {
			if (data.records.length === 1) {
				// 有一条数据返回，跳转详情页
				setRow({
					...data.records[0]
				});
				setOrderDetailVisible(true);
			} else {
				message.warning("获取订单信息失败");
			}
		}
	}

	async function getQueryAreaCode() {
		const { success, data } = await queryAreaCode({ areaCode: "" });
		if (success) {
			areaOption.current = data.map(e => {
				return {
					...e,
					value: e.id,
					label: e.name
				};
			});
		}
	}
	//拿货员列表
	const handleUserList = async username => {
		const { data, success } = await queryTakeUserList({ username, current: 1, size: 2000, businessType: 3 });
		if (success) {
			setUserData(data);
		}
	};

	//单个打印
	const handlePrint = record => {
		handleBatchPrint(4, [record]);
	};

	//点击日志
	const viewUniquecodeLog = (val) => {
		setRow(val);
		setVisible('UniqueCodeLog');
	}

	const handleTakeGoodsChange = value => {
		setTakeGoods(value);
	};

	const batchPushGoodsToSupplier = async (params, action) => {
		START_LOADING();
		const res = await batchPushGoods(params);
		if (res.success) {
			if (action == 'batch') {
				setPushData(res.data);
				setVisible(7);
			} else {
				message.success('推送成功');
			}
			const params = form.getFieldsValue();
			fetchList({
				...params,
				status: params.status || ['wait-pickup'],
				pushStatus: params.pushStatus || [0],
			});
		} else {
			if(!action) {
				message.error('推送失败，请稍后重试');
			}
		}
		END_LOADING();
	}

	const handlePushSupplier = async (record) => {
		if (record.pushStatus || !record.hasPrinter) {
			return Modal.info({
				title: '提示',
				icon: <IconFont type="iconjingshi"/>,
				content: record.pushStatus ? '该商品已推送，请勿重复推送' : '该供应商未安装打印机，无法推送',
				okText: '知道了',
			})
		}
		batchPushGoodsToSupplier([{ code: record.code, storeId: record.supplierId }]);
	}

	const { defaultColumns, valueData } = useColumns({
		handlePrint,
		fetchPage,
		refTimeSort,
		areaOption,
		takeGoods,
		AreaValue,
		viewUniquecodeLog,
		handleTakeGoodsChange,
		handleWarehouseChange,
		handleAreaValueChange,
		selectedWarehouse,
    handleOpenOrderDetailVisible,
		code: location.state?.orderSn,
		handlePushSupplier,
	});
	const [columns, setColumns] = useState(defaultColumns);
	const sortProps = {
		mode: "single",
		keepDataSource: true
	};

	const tableKey = "FmcmPurchase2165";
	const {
		selectedKeys,
		selectedRows,
		fetchList,
		dataSource,
		form,
		query,
		pagination,
		searchSimpleTableProps
	} = useTableConfig({
		tableKey,
		rowKey: "id",
		columns,
		tableRequest,
		autoFetch: true,
		pageSize: 500,
		pageSizeOptions: [50, 100, 500, 1000, 5000],
		hasPagination: true,
		sortProps,
		hasQuickSearch: true,
		beforeQuerySearch: ({ API_DATA }) => {
			getQueryAreaCode();
			setApiData(API_DATA);
			if (!API_DATA.status && !location.state?.orderSn) {
				API_DATA.status = ["wait-pickup"];
			}
			if (!API_DATA.timeType) {
				API_DATA.timeType = 3;
			}
			if (API_DATA?.orderLabelIdList) {
				API_DATA["excTypeSearchType"] = API_DATA?.orderLabelIdList?.isLabelOr;
				API_DATA["label"] = API_DATA?.orderLabelIdList?.containLabelIdArr || null;
				delete API_DATA.orderLabelIdList;
			} else {
				// 默认搜索只包含同时勾选的标签，标签默认勾选采购
				API_DATA["excTypeSearchType"] = 3
				API_DATA["label"] = ['2']
			}
			API_DATA["timeSort"] = refTimeSort?.current || null;
			if (API_DATA.codes) {
				API_DATA.codes = API_DATA.codes.split(',');
			}
			if (API_DATA.sourceSystemNo) {
				API_DATA.sourceSystemNo = API_DATA.sourceSystemNo.split(',');
			}
			if (API_DATA.outboundNo) {
				API_DATA.outboundNo = API_DATA.outboundNo.split(',');
			}
			if (API_DATA.deliverySystemNo) {
				API_DATA.deliverySystemNo = API_DATA.deliverySystemNo.split(',');
			}
			if (API_DATA.deliveryOutboundNo) {
				API_DATA.deliveryOutboundNo = API_DATA.deliveryOutboundNo.split(',');
			}
			if (API_DATA.warehouse) {
				API_DATA.warehouse = [API_DATA.warehouse];
			}
			if (API_DATA.uniqueCodes) {
				API_DATA.uniqueCodes = API_DATA.uniqueCodes.split(',');
			}
			if (API_DATA.afterSalesOrderNos) {
				API_DATA.afterSalesOrderNos = API_DATA.afterSalesOrderNos.split(',');
			}
			if (API_DATA.systemNos) {
				API_DATA.systemNos = API_DATA.systemNos.split(',');
			}
			if (API_DATA.outboundNos) {
				API_DATA.outboundNos = API_DATA.outboundNos.split(',');
			}
			if (API_DATA.logisticsNos) {
				API_DATA.logisticsNos = API_DATA.logisticsNos.split(',');
			}
			if (API_DATA.tradeNos) {
				API_DATA.tradeNos = API_DATA.tradeNos.split(',');
			}
			return { ...API_DATA };
		},
		resetSourceData: false,
		hasColsSetting: true,
		hasToggleSearchForm: true,
		columnResize: true
	});
	function fetchPage() {
		const DATA = form.getFieldValue();
		fetchList(DATA);
	}
	useEffect(() => {
		handleUserList();
	}, []);

	useEffect(() => {
		if (location.state && location.state?.orderSn) {
			form.resetFields();
			form.setFieldsValue({ codes: location.state.orderSn });
			let timer = setTimeout(() => {
				fetchPage();
				clearTimeout(timer);
				timer = null;
			},400)
		}
	}, [location.state?.orderSn])

	const CheckStockAndNoteProps = {
		visible,
		query,
		fetchList,
		checkedRows: selectedRows,
		dataSource,
		userData,
		areaOption,
		checkedIds: selectedKeys,
		handleOk() {
			updateTableList(selectedRows);
		},
		handleCancel() {
			setVisible(0);
		}
	};

	//拿货设置
	const NahuoConfigModalProps = {
		visible,
		handleCancel() {
			setVisible(false);
		}
	}

	//批量打印商品唯一吗
	const handleBatchPrint = async (type, value) => {
		//针对所选项
		let codes;
		let savePrintData;
		let printNum;
		if (type == '1') {
			if (!selectedRows.length) {
				return message.info("请选择需要打印的商品");
			}
			codes = selectedRows.map(v => v.code);
			printNum = selectedRows.length;
			savePrintData = selectedRows.map(v => {
				return {
					"outboundNo": v.outboundNo,
					"uniqueCode": v.code
				}
			})
		} else if (type == '2') {
			const totalDataCount = pagination.total;
			const batchSize = 1000;
			const data = await getAllData(totalDataCount, batchSize, type);
			if (!data?.length) {
				message.info("该页面无商品，无法打印");
				return;
			}
			codes = data.map(v => v.code);
			printNum = data.length;
			savePrintData = data.map(v => {
				return {
					"outboundNo": v.outboundNo,
					"uniqueCode": v.code
				}
			})
		} else if (type == '3') {
			const { data, success } = await getFmcgpurchasesList({});
			if (success) {
				const totalDataCount = data.total;
				const batchSize = 1000;
				const arr = await getAllData(totalDataCount, batchSize);
				if (!arr?.length) {
					message.info("该页面无商品，无法打印");
					return;
				}
				codes = arr.map(v => v.code);
				printNum = arr.length;
				savePrintData = arr.map(v => {
					return {
						"outboundNo": v.outboundNo,
						"uniqueCode": v.code
					}
				})
			}
		} else if (type == '4') {
			codes = value.map(v => v.code);
			printNum = value.length;
			savePrintData = value.map(v => {
				return {
					"outboundNo": v.outboundNo,
					"uniqueCode": v.code
				}
			})
		}
		if (!window.LODOP) {
			return message.info('请安装lodop打印组件并确保组件已开启');
		}
		START_LOADING();
		const { success, data } = await getKuaiMaiPrint({
			codes,
			labelType: 3
		})
		END_LOADING()
		if (success) {
			setPrintConfig({
				printData: JSON.parse(data),
				printNum,
				savePrintData
			});
			setVisible('printKmModal');
		}
	};

	async function fetchData(offset, limit, type) {
		return new Promise(resolve => {
			setTimeout(() => {
				if (type == 2) {
					ApiData.pageSize = limit;
					ApiData.isAllData = 1;
					ApiData.pageNum = offset / 1000 + 1;
					ApiData.storeIdSort = true;
					const response = getFmcgpurchasesList(ApiData);
					resolve(response);
				} else {
					const param = { isAllData: 1, pageSize: limit, pageNum: offset / 1000 + 1, storeIdSort: true };

					const response = getFmcgpurchasesList(param);
					resolve(response);
				}
			}, 100);
		});
	}

	async function getAllData(totalItems, pageSize, type) {
		const allData = [];
		let offset = 0;
		while (offset < totalItems) {
			const limit = Math.min(pageSize, totalItems - offset);
			const response = await fetchData(offset, limit, type);
			allData.push(...response.data.records);
			offset += limit;
		}

		return allData;
	}

	//更新打印状态
	async function sendDataToApi(chunk) {
		const response = await updatePrintStatus(chunk);
		return response;
	}

	//更新打印状态
	async function processData(list, chunkSize) {
		let startIndex = 0;
		let endIndex = chunkSize;
		while (startIndex < list.length) {
			if (endIndex > list.length) {
				endIndex = list.length;
			}
			const chunk = list?.slice(startIndex, endIndex);
			await sendDataToApi(chunk);
			startIndex += chunkSize;
			endIndex += chunkSize;
		}
	}

	const LeftBtns = (
		<Space>
			<SelectActions name="拿货指派" onClick={() => commonHandleClick(1)} />
			<SelectActions name="供应商指派" onClick={() => commonHandleClick(2)} />
			<SelectActions name="打印唯一码" options={printOptions} onClick={key => handleBatchPrint(key)} />
			<SelectActions name="商品异常" onClick={() => commonHandleClick(4)} />
			<SelectActions name="取消标记异常" onClick={() => commonHandleClick(5)} />
			<SelectActions name="批量推送" onClick={() => commonHandleClick(7)} />
			<SelectActions name="唯一码配置" onClick={() => commonHandleClick(6)} />
			<SelectActions
				onClick={key => {
					if (key === "导出勾选项") {
						handleExport(3);
					} else {
						handleExport(2);
					}
				}}
				options={[
					{
						label: "导出筛选项"
					},
					{
						label: "导出勾选项"
					}
				]}
			>
				<CloudDownloadOutlined className="main-color" />
				导出
			</SelectActions>
		</Space>
	);

	//列表右侧批量操作按钮
	const RightBtns = (
		<Space>
			<Button type="text" onClick={() => setVisible('nahuo')}>
				<IconFont type="icona-lujing11" />
				拿货设置
			</Button>
		</Space>
	)

	//快麦打印
	const PrintKmModalProps = {
		printConfig,
		updatePrintStatus(data) {
			if (data.length > 10000) {
				processData(data, 1000);
			} else {
				updatePrintStatus(data).then(res => {
					if (res.success) {
						fetchList();
					}
				});
			}
		},
		hanldeCancel() {
			setVisible(null);
		}
	}

	// TODO
	const BatchPushGoodsModalProps = {
		visible: visible == 7,
		handleCancel: () => {
			setVisible(0);
		},
		pushData,
	}

	const handleExport = (val) => {
		if (val == 2) {
			//针对筛选项
			const API_DATA = { ...ApiData };
			if (!API_DATA.status) {
				API_DATA.status = ["wait-pickup"];
			}
			if (!API_DATA.timeType) {
				API_DATA.timeType = 3;
			}
			if (API_DATA?.orderLabelIdList) {
				API_DATA["excTypeSearchType"] = API_DATA?.orderLabelIdList?.isLabelOr
				API_DATA["label"] = API_DATA?.orderLabelIdList?.containLabelIdArr || null;
				delete API_DATA.orderLabelIdList;
			}
			API_DATA["timeSort"] = refTimeSort?.current || null;
			const obj = {
				businessParam: JSON.stringify({
					...API_DATA,
					uuid: getCurrentUser().uuid,
					current: pagination.current, // 当前页
					size: 9000, // 每页的数量
					businessKey: 2
				}),
				taskType: 4007
			}
			setCreateTaskData(obj);
			setVisible("ProgressModal");
		} else if (val == 3) {
			if (selectedRows.length > 0) {
				const obj = {
					businessParam: JSON.stringify({
						uuid: getCurrentUser().uuid,
						codes: selectedRows.map(v => v.code),
						businessKey: 3
					}),
					taskType: 4007
				}
				setCreateTaskData(obj);
				setVisible("ProgressModal");
			} else {
				message.info('请选择需要导出的数据');
			}
		}
	}

	const realProps = {
		createTaskData, 
		onCancel() {
			setVisible("");
		}
	};

	const UniqueCodesProps = {
		row,
		handleCancel() {
			setRow({});
			setVisible(null);
		}
	}

	return (
		<>
			<SearchCheckboxTable key={tableKey} leftBtns={LeftBtns} rightBtns={RightBtns} mounted={false} {...searchSimpleTableProps} />
			{visible == 1 && <PickAssignmentModal {...CheckStockAndNoteProps} />}
			{visible == 2 && <SupplierAssignmentModal {...CheckStockAndNoteProps} />}
			{visible == 3 && <PrintOnlyCodeModal {...CheckStockAndNoteProps} />}
			{visible == 4 && <ProductAbnormalModal {...CheckStockAndNoteProps} />}
			{visible == 5 && <UnProductAbnormalModal {...CheckStockAndNoteProps} />}
			{visible == 6 && <OnlyCodeDispositionModal {...CheckStockAndNoteProps} />}
			{visible == 'nahuo' && <NahuoConfigModal {...NahuoConfigModalProps} />}
			{visible == 7 && <BatchPushGoodsModal {...BatchPushGoodsModalProps} />}
			{visible == "ProgressModal" && <ActionExportExcelModal {...realProps} />}
			{visible == "UniqueCodeLog" && <UniqueCodeLog {...UniqueCodesProps} />}
			{orderDetailVisible && (
				<OrderDetailModal
					item={row}
					orderList={searchSimpleTableProps?.dataSource || []}
					field="systemNo"
					showFooter={false}
					handleOk={() => {
						setOrderDetailVisible(false);
						fetchList();
					}}
					onCancel={() => {
						setOrderDetailVisible(false);
					}}
				/>
			)}
			{printVisible && (
				<CommonModal
					title={{ title: "唯一码打印" }}
					visible={printVisible}
					onCancel={handleCancel}
					width="553px"
					onOk={onOk}
					minHeight={138}
				>
					<Form form={formPrint} name="common-printer-select">
						<SubTitle symbol as="s2" title={`打印详情`} wrapStyle={{ marginBottom: 16 }} />
						<Form.Item style={{ margin: 8 }}>
							<div>
								<span>打印唯一码数量：</span>
								<span style={{ color: "rgba(240, 61, 41, 1)" }}>{printData.length}</span>
							</div>
						</Form.Item>
						{configObj && (
							<Form.Item label="" name="唯一码" style={{ margin: 8 }} rules={[{ required: true, message: "请先选择打印机" }]}>
								<Select placeholder="请选择打印机" onChange={handlePrinterName} value={configObj["唯一码"]}>
									{options}
								</Select>
							</Form.Item>
						)}
					</Form>
				</CommonModal>
			)}
			{/* {printVisible && <PrintModal {...PrintModalProps} />} */}
			{visible == 'printKmModal' && <PrintKmModal {...PrintKmModalProps} />}
		</>
	);
};

export default React.memo(FmcmPurchasePage, () => {
	return true;
});
